<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace App\Service\Log;


class LogFile
{


    // 增加一个当前url 用于保存日志中，便于查看日志
    protected $url;
    protected $log = [];

    /**
     * 配置参数
     * @var array
     */
    protected $config = [
        'time_format'  => 'c',
        'single'       => false,
        'file_size'    => 2097152,
        'path'         => '',
        'apart_level'  => [],
        'max_files'    => 0,
        'json'         => false,
        'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
        'format'       => '[%s][%s] %s',
    ];

    // 实例化并传入参数
    public function __construct($config = [])
    {
        if(is_array($config)){
            $this->config = array_merge($this->config, $config);
        }

        if(empty($this->config['format'])){
            $this->config['format'] = '[%s][%s] %s';
        }

        //$site   = $app->request->param('site', 'app');
        $module = request()->input('module', 'frontend');
        $ds     = DIRECTORY_SEPARATOR;
        if(empty($this->config['path'])){
            $this->config['path'] = getRuntimePath().'log'.$ds;
        }
        if(substr($this->config['path'], -1) != $ds){
            $this->config['path'] .= $ds;
        }

        // 日志 指定模块
        //$this->config['path'] .= $site.$ds.$module . $ds;
        $this->config['path'] .= $module.$ds;
    }

    // 设置路径


    /**
     * 记录日志信息
     * @access public
     * @param mixed $msg 日志信息
     * @param string $type 日志级别
     * @param array $context 替换内容
     * @param bool $lazy
     * @return $this
     */
    public function record($msg, string $type = 'info', array $context = [])
    {
        if(is_string($msg) && !empty($context)){
            $replace = [];
            foreach($context as $key => $val){
                $replace['{'.$key.'}'] = $val;
            }

            $msg = strtr($msg, $replace);
        }

        if(!empty($msg) || 0 === $msg){
            $this->log[$type][] = $msg;
        }

        $this->save();

        return $this;
    }


    /**
     * 保存日志
     * @return bool
     */
    public function save():bool
    {
        $log = $this->log;
        if($this->saveLog($log)){
            return true;
        }

        return false;
    }

    #################################################################################

    /**
     * 获取日志信息
     * @access public
     * @param string $channel 日志通道名
     * @return array
     */
    public function getLog(string $channel = null):array
    {
        return [];
    }

    /**
     * 实时写入日志信息
     * @access public
     * @param mixed $msg 调试信息
     * @param string $type 日志级别
     * @param array $context 替换内容
     * @return $this
     */
    public function write($msg, string $type = 'info', array $context = [])
    {
        return $this->record($msg, $type, $context, false);
    }

    /**
     * 记录日志信息
     * @access public
     * @param string $level 日志级别
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function log($level, $message, array $context = []):void
    {
        $this->record($message, $level, $context);
    }

    /**
     * 记录emergency信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function emergency($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录警报信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function alert($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录紧急情况
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function critical($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录错误信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function error($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录warning信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function warning($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录notice信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function notice($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录一般信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function info($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录调试信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function debug($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    /**
     * 记录sql信息
     * @access public
     * @param mixed $message 日志信息
     * @param array $context 替换内容
     * @return void
     */
    public function sql($message, array $context = []):void
    {
        $this->log(__FUNCTION__, $message, $context);
    }

    public function __call($method, $parameters)
    {
        $this->log($method, ...$parameters);
    }

    #################################################################################

    /**
     * 日志写入接口
     * @access public
     * @param array $log 日志信息
     * @return bool
     */
    public function saveLog(array $log):bool
    {
        $destination = $this->getMasterLogFile();

        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);

        $info = [];

        // 日志信息封装
        $time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);

        foreach($log as $type => $val){
            $message = [];
            foreach($val as $msg){
                if(!is_string($msg)){
                    $msg = var_export($msg, true);
                }

                $message[] = $this->config['json'] ?
                    json_encode(['time' => $time, 'type' => $type, 'msg' => $msg], $this->config['json_options']) :
                    sprintf($this->config['format'], $time, $type, $msg);
            }

            if(true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])){
                // 独立记录的日志级别
                $filename = $this->getApartLevelFile($path, $type);
                $this->write($message, $filename, true);

                // TODO 如果独立记录某些日志，总日志就不记录了
                //   如果总日志还需要记录，则注释下面的 continue
                // continue;
            }

            $info[$type] = $message;
        }

        if($info){
            return $this->writeLog($info, $destination);
        }

        return true;
    }


    #################################################################################
    // 获取当前url
    protected function getUrl()
    {
        if(empty($this->url)){
            $this->url = chr(10).request()->url(true);
        }

        return $this->url;
    }

    /**
     * 日志写入
     * @access protected
     * @param array $message 日志信息
     * @param string $destination 日志文件
     * @return bool
     */
    protected function writeLog(array $message, string $destination, $addHost = false):bool
    {
        // 检测日志文件大小，超过配置大小则备份日志文件重新生成
        $this->checkLogSize($destination);

        $info = [];

        foreach($message as $type => $msg){
            // 增加空行
            $pre = '';
            if($type == 'HOST'){
                $pre = PHP_EOL;
            }
            $info[$type] = $pre.(is_array($msg) ? implode(PHP_EOL, $msg) : $msg);
        }

        // 增加请求的url 独立日志中
        $message = ($addHost ? $this->getUrl().'  ' : '').implode(PHP_EOL, $info).PHP_EOL;

        return error_log($message, 3, $destination);
    }

    /**
     * 获取主日志文件名
     * @access public
     * @return string
     */
    protected function getMasterLogFile():string
    {

        if($this->config['max_files']){
            $files = glob($this->config['path'].'*.log');

            try{
                if(count($files) > $this->config['max_files']){
                    unlink($files[0]);
                }
            } catch(\Exception $e){
                //
            }
        }

        if($this->config['single']){
            $name     = is_string($this->config['single']) ? $this->config['single'] : 'single';
            $filename = $name.'.log';
        } else{
            if($this->config['max_files']){
                $filename = date('Ymd').'.log';
            } else{
                $filename = date('Ym').DIRECTORY_SEPARATOR.date('d').'.log';
            }
        }

        $destination = $this->config['path'].$filename;

        return $destination;
    }

    /**
     * 获取独立日志文件名
     * @access public
     * @param string $path 日志目录
     * @param string $type 日志类型
     * @return string
     */
    protected function getApartLevelFile(string $path, string $type):string
    {

        if($this->config['single']){
            $name = is_string($this->config['single']) ? $this->config['single'] : 'single';

            $name .= '_'.$type;
        } elseif($this->config['max_files']){
            $name = date('Ymd').'_'.$type;
        } else{
            $name = date('d').'_'.$type;
        }

        return $path.DIRECTORY_SEPARATOR.$name.'.log';
    }

    /**
     * 检查日志文件大小并自动生成备份文件
     * @access protected
     * @param string $destination 日志文件
     * @return void
     */
    protected function checkLogSize(string $destination):void
    {
        if(is_file($destination) && floor($this->config['file_size']) <= filesize($destination)){
            try{
                rename($destination, dirname($destination).DIRECTORY_SEPARATOR.time().'-'.basename($destination));
            } catch(\Exception $e){
                //
            }
        }
    }
}
